<template>
  <!--画布涂鸦 -->
  <div class="drawing-container">

    <div class="canvas-wrapper">
      <canvas ref="canvasRef" @mousedown="startDrawing" @mousemove="draw" @mouseup="stopDrawing"
        @mouseleave="handleMouseLeave" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
        @touchend="handleTouchEnd" @mouseenter="setCursorToPen"></canvas>
    </div>
    <div class="toolbar">
      <button @click="undo" :disabled="history.length <= 1">撤销</button>
      <button @click="clearCanvas">清空</button>
      <button @click="saveDrawing">保存</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';

const canvasRef = ref(null);
const ctx = ref(null);
const isDrawing = ref(false);
const currentColor = ref('black');
const currentSize = ref(5);
const history = ref([]);
const historyIndex = ref(-1);

// 初始化画布
onMounted(() => {
  const canvas = canvasRef.value;
  ctx.value = canvas.getContext('2d');

  // 设置画布大小
  resizeCanvas();

  // 初始化历史记录
  saveState();

  // 添加窗口大小变化监听
  window.addEventListener('resize', resizeCanvas);
});

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeCanvas);
})

// 调整画布大小
function resizeCanvas() {
  const canvas = canvasRef.value;
  const container = canvas.parentElement;

  canvas.width = container.clientWidth;
  canvas.height = container.clientHeight;

  // 重新绘制当前状态
  if (history.value.length > 0) {
    restoreState();
  }
}

// 设置鼠标为笔样式
function setCursorToPen() {
  // const canvas = canvasRef.value;
  updateCursorColor(currentColor.value);
}

// 处理鼠标离开画布
function handleMouseLeave() {
  stopDrawing();
  // 不再重置鼠标样式，保持笔样式
}

// 开始绘制
function startDrawing(e) {
  isDrawing.value = true;
  draw(e);
}

// 绘制中
function draw(e) {
  if (!isDrawing.value || !ctx.value) return;

  // 获取鼠标位置
  const rect = canvasRef.value.getBoundingClientRect();
  const x = (e.clientX || e.touches?.[0].clientX) - rect.left;
  const y = (e.clientY || e.touches?.[0].clientY) - rect.top;

  ctx.value.lineJoin = 'round';
  ctx.value.lineCap = 'round';
  ctx.value.strokeStyle = currentColor.value;
  ctx.value.lineWidth = currentSize.value;

  ctx.value.lineTo(x, y);
  ctx.value.stroke();
  ctx.value.beginPath();
  ctx.value.moveTo(x, y);
}

// 结束绘制
function stopDrawing() {
  if (isDrawing.value) {
    isDrawing.value = false;
    ctx.value.beginPath();
    saveState();
  }
}

// 触摸事件处理
function handleTouchStart(e) {
  e.preventDefault();
  startDrawing(e);
}

function handleTouchMove(e) {
  e.preventDefault();
  draw(e);
}

function handleTouchEnd(e) {
  e.preventDefault();
  stopDrawing();
}

// 更新笔的颜色
function updateCursorColor(color) {
  const canvas = canvasRef.value;
  const svg = `<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M15.5 0.5L0.5 15.5L3.5 15.5L15.5 3.5L15.5 0.5Z' fill='${color}' stroke='${color}'/></svg>`;
  canvas.style.cursor = `url("data:image/svg+xml;utf8,${encodeURIComponent(svg)}") 0 16, auto`;
}

// 保存当前画布状态
function saveState() {
  // 如果撤销后进行了新的绘制，删除后面的历史记录
  if (historyIndex.value < history.value.length - 1) {
    history.value = history.value.slice(0, historyIndex.value + 1);
  }

  const canvas = canvasRef.value;
  const imageData = ctx.value.getImageData(0, 0, canvas.width, canvas.height);
  history.value.push(imageData);
  historyIndex.value = history.value.length - 1;
}

// 恢复历史状态
function restoreState(index = historyIndex.value) {
  if (index >= 0 && index < history.value.length) {
    ctx.value.putImageData(history.value[index], 0, 0);
  }
}

// 撤销操作
function undo() {
  if (historyIndex.value > 0) {
    historyIndex.value--;
    restoreState(historyIndex.value);
  }
}

// 清空画布
function clearCanvas() {
  ctx.value.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height);
  saveState();
}

// 保存绘图
async function saveDrawing() {
  const canvas = canvasRef.value;

  // 将画布转换为Base64格式
  const imageData = canvas.toDataURL('image/png');

  try {
    // 这里替换为你的API调用
    const response = await fetch('your-api-endpoint', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ image: imageData }),
    });

    if (response.ok) {
      alert('绘图保存成功！');
    } else {
      throw new Error('保存失败');
    }
  } catch (error) {
    console.error('保存绘图时出错:', error);
    alert('保存绘图时出错，请重试');
  }
}
</script>

<style scoped>
.drawing-container {
  display: flex;
  flex-direction: column;
  height: 60vh;
  width: 500px;
}

.toolbar {
  display: flex;
  gap: 8px;
  padding: 10px;
  background: #f0f0f0;
  flex-wrap: wrap;
}

.toolbar button {
  padding: 5px 10px;
  cursor: pointer;
}

.toolbar button.active {
  background-color: #007bff;
  color: white;
}

.toolbar button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.canvas-wrapper {
  width: 500px;
  height: 400px;
  border: 1px solid #ccc;
  flex: 1;
  position: relative;
  overflow: hidden;
}

canvas {
  background-color: white;
  display: block;
  touch-action: none;
  /* 防止触摸时页面滚动 */
  cursor: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='0 0 16 16'><path d='M15.5 0.5L0.5 15.5L3.5 15.5L15.5 3.5L15.5 0.5Z' fill='black' stroke='black'/></svg>") 0 16, auto;
}
</style>